package table_comm

import (
	"fmt"
	"time"

	"gitee.com/klein-x/biz/model/mysql/table"
	"gitee.com/klein-x/biz/module/db/mysql"
)

type Order struct {
	ID          string    `gorm:"type:char(20);primaryKey;unique;not null;comment:'订单号'"`    // 商户订单号，唯一
	UserID      string    `gorm:"type:char(36);not null;comment:'用户ID'"`                     // 下单用户的ID
	GoodsID     string    `gorm:"type:char(36);not null;comment:'商品ID'"`                     // 购买的商品ID
	GoodsName   string    `gorm:"type:char(36);not null;comment:'商品名称'"`                     // 商品名称
	Price       uint64    `gorm:"default:0;comment:'商品价格'"`                                  // 商品价格
	Quantity    uint      `gorm:"default:0;comment:'购买数量'"`                                  // 商品购买数量
	TotalAmount uint64    `gorm:"default:0;comment:'订单总金额'"`                                 // 订单总金额
	Status      string    `gorm:"type:char(1);default:0;comment:'订单状态，未支付0,待支付1,已支付2、已完成3'"` // 订单状态，未支付0,待支付1,已支付2、已完成3
	PaymentID   string    `gorm:"type:char(32);not null;comment:'支付记录ID'"`                   // 支付记录ID，关联支付记录表的外键（如果有）
	CreatedAt   time.Time `gorm:"comment:'创建时间'"`
	UpdatedAt   time.Time `gorm:"comment:'更新时间'"`
}

func OrderInsert(order *Order) error {
	db := mysql.GetGlobalDB()
	return table.InsertCheck(db.Create(order))
}

func OrderExists(key string) (bool, error) {
	order, err := OrderGetByKey(key)
	return order != nil, err // 记录存在，返回true
}

func OrderGetByKey(key string) (*Order, error) {
	db := mysql.GetGlobalDB()
	var order Order
	return table.SelectCheck(&order, db.Where("id=?", key).First(&order))
}

func OrderGetByUser(uuid string) (*[]Order, error) {
	db := mysql.GetGlobalDB()
	var orders []Order
	return table.SelectCheck(&orders, db.Where("user_id = ?", uuid).Order("created_at desc").Find(&orders))
}
func OrderGetByKeyAndUser(key string, uuid string) (*Order, error) {
	db := mysql.GetGlobalDB()
	var order Order
	return table.SelectCheck(&order, db.Where("id = ? AND user_id = ?", key, uuid).Find(&order))
}

func OrderUpdate(order *Order) error {
	db := mysql.GetGlobalDB()
	return table.UpdateCheck(db.Save(order))
}

func DeleteOrderByKey(orderId uint) error {
	db := mysql.GetGlobalDB()
	return table.DeleteCheck(db.Delete(&Order{}, orderId))
}

func OrderGetByStatus(status string) (*[]Order, error) {
	db := mysql.GetGlobalDB()
	var orders []Order
	return table.SelectCheck(&orders, db.Where("status = ?", status).Find(&orders))
}

func GetOrdersWithPagination(page int, pageSize int) ([]Order, error) {
	db := mysql.GetGlobalDB()
	var orders []Order
	result := db.Limit(pageSize).Offset((page - 1) * pageSize).Find(&orders)
	if result.Error != nil {
		return nil, result.Error
	}
	return orders, nil
}

// 分页查询页面数
func OrderGetTotalPagesByUserID(userID string, pageSize int) (int, error) {
	db := mysql.GetGlobalDB()
	var count int64
	newCount, err := table.SelectCheck(&count, db.Model(&Order{}).Where("user_id = ?", userID).Count(&count))
	if err != nil {
		return 0, err
	}
	if newCount == nil {
		return 0, nil
	}

	totalPages := int(*newCount) / pageSize
	if int(*newCount)%pageSize != 0 {
		totalPages++ // 如果有余数，则总页数需要+1
	}
	return totalPages, nil
}

// 分页查询页数据
func OrdersGetByUserIDWithPagination(userID string, page int, pageSize int) (*[]Order, error) {
	db := mysql.GetGlobalDB()
	var orders []Order
	// 检查页码和页大小的有效性
	if page <= 0 || pageSize <= 0 {
		return nil, fmt.Errorf("invalid page or page size")
	}
	return table.SelectCheck(&orders, db.Where("user_id = ?", userID).Limit(pageSize).Offset((page-1)*pageSize).Find(&orders))
}
